<template>
  <div class="users-manage p-4">
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2">
      <el-input
        v-model="queryParams.userName"
        placeholder="请输入账号"
        style="width: 200px"
        clearable
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
      <el-button
        type="danger"
        plain
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
      <el-button plain @click="handleImport">
        <el-icon><Download /></el-icon>
        导入
      </el-button>
      <el-button plain @click="handleExport">
        <el-icon><Upload /></el-icon>
        导出
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="头像" width="80" align="center">
        <template #default="scope">
          <el-avatar
            :size="40"
            :src="
              scope.row.avatar ||
              'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
            "
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" min-width="100" />
      <el-table-column prop="username" label="账号" min-width="100" />
      <el-table-column label="性别" width="80" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.gender === 1 ? 'primary' : 'danger'"
            size="small"
          >
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" min-width="120" />
      <el-table-column label="角色" min-width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.roles === 1" type="success">管理员</el-tag>
          <el-tag v-else-if="scope.row.roles === 2" type="info">学生</el-tag>
          <el-tag v-else type="warning">{{ scope.row.roleNames }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="部门" min-width="100">
        <template #default="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <div class="flex space-x-2">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              plain
              :disabled="scope.row.id === 1"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              :disabled="scope.row.id === 1"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="queryParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 用户添加/编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="dialogTitle"
      :direction="direction"
      size="380px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNum">
          <el-input v-model="userForm.idNum" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="1" :value="1">男</el-radio>
            <el-radio :label="2" :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-select v-model="userForm.deptId" placeholder="请选择部门">
            <el-option
              v-for="item in deptMapList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleList">
          <el-select
            v-model="userForm.roles"
            placeholder="选择角色"
            multiple
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{
          userDetail.id
        }}</el-descriptions-item>
        <el-descriptions-item label="账号">{{
          userDetail.username
        }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{
          userDetail.name
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          userDetail.phone
        }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{
          userDetail.idNum
        }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{
          userDetail.gender === 1 ? '男' : '女'
        }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{
          userDetail.deptName
        }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <template
            v-if="
              Array.isArray(userDetail.roles) && userDetail.roles.length > 0
            "
          >
            <el-tag
              v-for="roleId in userDetail.roles"
              :key="roleId"
              class="mr-1 mb-1"
              :type="getRoleTagType(roleId)"
              effect="plain"
              disable-transitions
            >
              {{ getRoleName(roleId) }}
            </el-tag>
          </template>
          <el-tag v-else-if="userDetail.roleList === 1" type="success"
            >管理员</el-tag
          >
          <el-tag v-else-if="userDetail.roleList === 2" type="info"
            >学生</el-tag
          >
          <el-tag v-else type="warning">{{ userDetail.roleNames }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          userDetail.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          userDetail.updateTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  userlist,
  createuser,
  updatauser,
  getuserbyid,
} from '@/api/usersManage.js'
import { getdeptlist } from '@/api/dept.js'
import { getrole } from '@/api/role.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phone: '',
  deptId: undefined,
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const selectedRows = ref([])
const jumpPage = ref(1)

// 抽屉相关
const drawerVisible = ref(false)
// 抽屉Title
const dialogTitle = ref('添加用户')
const direction = ref('rtl') // 从右向左打开
const userFormRef = ref(null)
const userForm = reactive({
  id: undefined,
  username: '',
  name: '',
  phone: '',
  idNum: '',
  gender: 1,
  deptId: undefined,
  roles: undefined,
})

// 部门表映射
const deptMapList = ref([])
const isCreate = ref(true)
// 角色列表
const rolesList = ref([])

// 用户详情对话框
const detailDialogVisible = ref(false)
const userDetail = reactive({
  id: '',
  username: '',
  name: '',
  phone: '',
  idNum: '',
  gender: 1,
  deptId: '',
  deptName: '',
  roles: '',
  createTime: '',
  updateTime: '',
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
  idNum: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号',
      trigger: 'blur',
    },
  ],
  gender: [{ required: false, message: '请选择性别', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  roleList: [{ required: false, message: '请选择角色', trigger: 'change' }],
}

// 获取部门信息
const getDeptList = async () => {
  const { res, data } = await getdeptlist()
  const newMap = data.records.map((item) => {
    return { id: item.id, deptName: item.deptName }
  })
  deptMapList.value = newMap
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const { code, data } = await userlist(queryParams)

    if (code == 500) {
      ElMessage.error('获取用户数据失败')
    }
    // 覆盖数据
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRolesList = async () => {
  const { res, data } = await getrole({
    roleName: '',
    pageNum: 1,
    pageSize: 10,
  })
  const newRoles = data.records.map((item) => {
    return { id: item.id, deptName: item.roleName }
  })
  rolesList.value = newRoles
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getUserList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getUserList()
}

// 添加页面跳转功能
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (
    isNaN(pageNum) ||
    pageNum < 1 ||
    pageNum > Math.ceil(total.value / queryParams.pageSize)
  ) {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = queryParams.pageNum
    return
  }
  queryParams.pageNum = pageNum
  getUserList()
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getUserList()
}

// 处理添加
const handleAdd = () => {
  dialogTitle.value = '添加用户'
  isCreate.value = true
  // 重置表单
  Object.keys(userForm).forEach((key) => {
    userForm[key] = key === 'gender' ? 1 : undefined
  })
  drawerVisible.value = true
  // 在表单显示后重置校验结果
  setTimeout(() => {
    userFormRef.value?.resetFields()
  }, 0)
}

// 处理编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑用户'
  isCreate.value = false
  // 填充表单数据
  const { code, data } = await getuserbyid(row.id)
  if (code !== 200) {
    ElMessage.error('获取用户信息失败')
    return
  }
  Object.keys(userForm).forEach((key) => {
    userForm[key] = data[key]
  })
  drawerVisible.value = true
}

// 处理详情
const handleDetail = async (row) => {
  const { code, data } = await getuserbyid(row.id)
  if (code !== 200) {
    ElMessage.error('获取用户信息失败')
    return
  }
  // 填充详情数据
  Object.keys(userDetail).forEach((key) => {
    userDetail[key] = data[key] || ''
  })
  detailDialogVisible.value = true
}

// 处理提交表单
const submitForm = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      if (isCreate.value) {
        // 添加
        const { code, msg } = await createuser(userForm)
        if (code !== 200) {
          ElMessage.error('添加失败' + msg)
          return
        }
        ElMessage.success('添加成功')
      } else {
        // 修改
        const { code, msg } = await updatauser(userForm)
        if (code !== 200) {
          ElMessage.error(msg)
          return
        }
        ElMessage.success('修改成功')
      }

      drawerVisible.value = false
      getUserList()
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 这里应该调用删除API
      ElMessage.success('删除成功')
      getUserList()
    })
    .catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的用户')
    return
  }

  const names = selectedRows.value.map((item) => item.name).join('、')
  ElMessageBox.confirm(`确定要删除以下用户吗？\n${names}`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 这里应该调用批量删除API
      ElMessage.success('批量删除成功')
      getUserList()
    })
    .catch(() => {})
}

// 处理导入
const handleImport = () => {
  // 这里应该处理导入逻辑
  ElMessage.info('导入功能开发中')
}

// 处理导出
const handleExport = () => {
  // 这里应该处理导出逻辑
  ElMessage.info('导出功能开发中')
}

// 根据角色ID获取角色名称
const getRoleName = (roleId) => {
  const role = rolesList.value.find((item) => item.id === roleId)
  return role ? role.deptName : `角色${roleId}`
}

// 根据角色ID获取标签类型
const getRoleTagType = (roleId) => {
  // 这里可以根据不同角色ID返回不同的标签类型
  if (roleId === 1) return 'success'
  if (roleId === 2) return 'success'
  if (roleId === 3) return 'info'
  return 'warning'
}

// 监听userName变化，实现防抖搜索
let searchTimer = null
watch(
  () => queryParams.userName,
  (newVal) => {
    if (searchTimer) clearTimeout(searchTimer)
    searchTimer = setTimeout(() => {
      handleSearch()
    }, 500) // 500毫秒防抖
  }
)

onMounted(() => {
  // 获取用户列表
  getUserList()
  // 获取部门列表
  getDeptList()
  // 获取角色列表
  getRolesList()
})
</script>

<style lang="less" scoped>
.users-manage {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-table {
    height: calc(100vh - 270px);
  }
}
</style>
